package cj.primariaiquest.web;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cj.primariaiquest.model.Department;
import cj.primariaiquest.model.Ticket;
import cj.primariaiquest.ws.endpoint.WebServiceClient;
import cj.primariaiquest.ws.exceptions.WebServiceException;

@Component
public class CancelTicketServlet extends HttpServlet {

    private static final long serialVersionUID = 7896884660320028616L;
    /**
     * Web service client used to send requests to the web service.
     */
    private static WebServiceClient webServiceClient;

    @Autowired
    public void setWebServiceClient(WebServiceClient webServiceClient) {
	CancelTicketServlet.webServiceClient = webServiceClient;
    }

    /**
     * When Submit button is pressed, this method will handle the data and send
     * a CancelTicketReqeust to the web service.
     */
    @Override
    protected void doGet(HttpServletRequest request,
	    HttpServletResponse response) throws ServletException, IOException {
	String address = "/WEB-INF/jsp/cancelTicketSucces.jsp";
	String dep = request.getParameter("dep");

	long number;
	try {
	    number = Long.parseLong(request.getParameter("number"));
	    webServiceClient.sendCancelTicketRequest(dep, number);

	    // add ticket to request so that we can access it's properties.
	    Ticket ticket = new Ticket();
	    ticket.setDepartment(Department.valueOf(dep));
	    ticket.setNumber(number);
	    request.setAttribute("ticket", ticket);
	} catch (WebServiceException e) {
	    address = "/WEB-INF/jsp/cancelTicketFailure.jsp";
	} catch (NumberFormatException e) {
	    address = "/WEB-INF/jsp/cancelTicketFailure.jsp";
	}

	RequestDispatcher dispatcher = request.getRequestDispatcher(address);
	dispatcher.forward(request, response);
    }
}
